package com.yb.livewykt.net

import com.google.gson.Gson
import com.yb.livewykt.util.SaveUserData
import okhttp3.*
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.*
import java.util.concurrent.TimeUnit

class RetrofitUtil {


    companion object{
        private lateinit var retrofit: Retrofit


        private var instance:RetrofitUtil? = null
        get() {
            if (field == null){
                field = RetrofitUtil()
            }
            return field
        }

        fun get() : RetrofitUtil{
            val builder = OkHttpClient().newBuilder()
                .addInterceptor(LiveInterceptor())
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)

            retrofit = Retrofit.Builder()
                .client(builder.build())
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(LiveUrl.baseUrl)
                .build()
            return instance!!
        }

    }
    fun <T> createService(clazz: Class<T>) : T {
        return retrofit.create(clazz)
    }


    class LiveInterceptor : Interceptor{
        override fun intercept(chain: Interceptor.Chain): Response {
            val builder = chain.request().newBuilder()
            builder.addHeader("token",SaveUserData.get().token)
            builder.addHeader("uuid", SaveUserData.get().uuid)
            return chain.proceed(builder.build())
        }

    }

    /**
     * 通过参数 Map 合集
     * @param paramsMap
     * @return
     */
    fun createJsonRequest(paramsMap: HashMap<String, Any>): RequestBody {
        val strEntity = Gson().toJson(paramsMap)
        return RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), strEntity)
    }

    /**
     * 通过参数 Object 合集
     * @param o
     * @return
     */
    fun createJsonRequest(o: Any): RequestBody {
        val strEntity = Gson().toJson(o)
        return RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), strEntity)
    }

}